package com.xscha.tableforge.controller;

import com.xscha.tableforge.model.entity.ViewMeta;
import com.xscha.tableforge.model.vo.ViewMetaVo;
import com.xscha.tableforge.model.vo.PageReq;
import com.xscha.tableforge.model.vo.PageResult;
import com.xscha.soyue.common.core.domain.R;
import com.xscha.tableforge.service.ViewMetaService;
import com.xscha.soyue.common.core.utils.BeanMapperUtils;
import com.xscha.tableforge.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/views")
public class ViewMetaController {

    private final ViewMetaService viewMetaService;

    @Autowired
    public ViewMetaController(ViewMetaService viewMetaService) {
        this.viewMetaService = viewMetaService;
    }

    @GetMapping("/table/{tableId}")
    public R<List<ViewMetaVo>> getViewsByTableId(@PathVariable String tableId) {
        List<ViewMeta> views = viewMetaService.findAllByTableId(tableId);
        return R.ok(BeanMapperUtils.mapAsList(views, ViewMetaVo.class));
    }
    
    @PostMapping("/table/{tableId}/page")
    public R<PageResult<ViewMetaVo>> getViewsByTableIdPage(
            @PathVariable String tableId,
            @RequestBody PageReq pageRequest) {
        PageResult<ViewMeta> result = viewMetaService.findPageByTableId(tableId, pageRequest);
		List<ViewMetaVo> viewMetaVos = BeanMapperUtils.mapAsList(result.getRecords(), ViewMetaVo.class);
		return R.ok(PageResult.of(viewMetaVos, result.getTotal(), result.getPageNum(), result.getPageSize()));
    }

    @GetMapping("/{id}")
    public R<ViewMetaVo> getViewById(@PathVariable String id) {
        return viewMetaService.findById(id)
                .map(view -> R.ok(BeanMapperUtils.map(view, ViewMetaVo.class)))
                .orElse(R.fail("视图不存在"));
    }

    @PostMapping
    public R<ViewMetaVo> createView(@RequestBody ViewMeta viewMeta) {
        try {
            ViewMeta createdView = viewMetaService.createView(viewMeta, SecurityUtils.getUserId());
            return R.ok(BeanMapperUtils.map(createdView, ViewMetaVo.class));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @PutMapping
    public R<ViewMetaVo> updateView(@RequestBody ViewMeta viewMeta) {
        try {
            ViewMeta updatedView = viewMetaService.updateView(viewMeta, SecurityUtils.getUserId());
            return R.ok(BeanMapperUtils.map(updatedView, ViewMetaVo.class));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public R<Void> deleteView(@PathVariable String id) {
        try {
            viewMetaService.deleteView(id, SecurityUtils.getUserId());
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}